package dongze.com.ckdj.data.gson;

import android.util.Log;

import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import dongze.com.ckdj.util.MyLog;


/**
 * Created by fanqwz on 2017/8/14.
 */

public class GsonArrayNullAdapter implements JsonDeserializer<List> {
    private static final String TAG = GsonArrayNullAdapter.class.getSimpleName();

    @Override
    public List deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        if (json.isJsonArray() || typeOfT instanceof List) {
            JsonArray arr = null;
            try {
                arr = json.getAsJsonArray();
            } catch (Exception e) {
                json.getAsJsonNull();
                MyLog.e(TAG, "deserialize: fail for " + typeOfT + ", json=" + json, e);
                return null;
            }

            if (arr == null)
                return new ArrayList(0);

            if (((ParameterizedType) typeOfT).getActualTypeArguments() == null
                    || ((ParameterizedType) typeOfT).getActualTypeArguments().length == 0) {
                MyLog.e(TAG, "deserialize: param not exist");
                return null;
            }

            try {
                List list = new ArrayList(arr.size());
                for (JsonElement e :
                        arr) {
                    list.add(context.deserialize(e, ((ParameterizedType) typeOfT).getActualTypeArguments()[0]));
                }

                return list;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
